/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-01 12:03:41
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-09-03 02:40:48
 * @FilePath: \keep_motion_api\models\product\order.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// 订单模型
const orderSchema = new Schema({
  user_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'User',
    required: true 
  },
  items: [{
    item_type: { 
      type: String, 
      enum: ["product", "course"],
      required: true 
    },
    product_id: { 
      type: Schema.Types.ObjectId, 
      ref: 'Product' 
    },
    course_id: { 
      type: Schema.Types.ObjectId, 
      ref: 'Course' 
    },
    quantity: Number,
    price: Number,
    discount_applied: Number
  }],
  total_amount: Number,
  status: {
    type: String,
    enum: ["pending", "paid", "shipped", "completed", "cancelled"],
    default: "pending"
  },
  create_time: { type: Date, default: Date.now },
  payment_time: Date,
  shipping_address: Object,
  applied_activities: [{
    activity_id: { 
      type: Schema.Types.ObjectId, 
      ref: 'ProductActivity' 
    },
    discount_amount: Number
  }]
});
orderSchema.methods.getOrders = async function() {
  return await this.model('Order').find();
}
orderSchema.methods.getOrderById = async function(orderId) {
  return await this.model('Order').findById(orderId);
}
orderSchema.methods.updateStatus = async function(orderId, status) {
  return await this.model('Order').findByIdAndUpdate(orderId, { status });
}
orderSchema.methods.refundOrder = async function(orderId) {
  return await this.model('Order').findByIdAndUpdate(orderId, { status: 'refunded' });
}
orderSchema.methods.exportOrders = async function() {
  return await this.model('Order').find().lean();
}
module.exports = mongoose.model('Order', orderSchema);
